package edu.gyc.hishiro.service.impl;

import edu.gyc.hishiro.model.*;
import edu.gyc.hishiro.dao.UserInfoDao;
import edu.gyc.hishiro.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ls
 * @since 2020-06-21
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfo> implements UserInfoService {
@Autowired
    SysUserRoleService userRoleService;
@Autowired
    SysRolePermissionService rolePermissionService;
@Autowired
 SysRoleService roleService;
@Autowired
    SysPermissionService permissionService;
    @Override
    public UserInfo findByUsername(String name) {
        UserInfo userInfo=lambdaQuery().eq(UserInfo::getUsername,name).one();
        if (userInfo != null) {
             List<SysUserRole> userRoles=userRoleService.lambdaQuery().eq(SysUserRole::getUid,userInfo.getUid())
                     .list();

            List<Integer> roleIds = new ArrayList<>();
            List<SysRole> roles = new ArrayList<>();
            List<SysRolePermission> rolePermissions = new ArrayList<>();

            if (userRoles.size() > 0) {
                List<SysPermission> permissions = new ArrayList<>();
                for(SysUserRole userRole:userRoles){
                    roleIds.add(userRole.getRoleId());
                }
                if (roleIds.size() > 0) {
                    for (Integer roleId : roleIds) {


                       SysRole role=  roleService.lambdaQuery().eq(SysRole::getId,roleId).one();
                        roles.add(role);
                    }
                    userInfo.setRoleList(roles);
                    for (Integer roleId : roleIds) {
                      rolePermissions=rolePermissionService.lambdaQuery().
                                eq(SysRolePermission::getRoleId,roleId)
                                .list();


                    }
                    if (rolePermissions.size() > 0) {
                        for (SysRolePermission rolePermission : rolePermissions) {
                              SysPermission permission=permissionService.lambdaQuery()
                                      .eq(SysPermission::getId,rolePermission.getPermissionId())
                                      .one();
                            permissions.add(permission);
                        }



                    }


                }

                for (SysRole role : roles) {
                    role.setPermissions(permissions);
                }
            }


        }
        return userInfo;
    }
}
